package com.impetus.project.skilltest.server.service;

import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.impetus.project.skilltest.client.stub.SecurityService;
import com.impetus.project.skilltest.common.SkillTestException;
import com.impetus.project.skilltest.common.dataobject.Candidate;
import com.impetus.project.skilltest.server.dao.CandidateDAO;

public class SecurityServiceImpl extends RemoteServiceServlet implements SecurityService{
	// List of users/candidates logged in
	
	private static final long serialVersionUID = -7264700841601486313L;
	private static Logger logger = Logger.getLogger(SecurityServiceImpl.class.getName());
	
	// List of users/candidates logged in
	private static Map<String,Candidate> session = new TreeMap<String, Candidate>();
	

	public Candidate login(String userid, String password)
	throws SkillTestException
	{
		Candidate candidate = CandidateDAO.getCandidateByUserNamePassword(userid, password);
		if (null != candidate)
		{
			logger.log(Level.INFO, "Adding session entry for " + userid);
			session.put(userid, candidate);
			
			// set the candidate object as a HTTP session attribute
			this.getThreadLocalRequest().getSession(true).setAttribute("candidate", candidate);
		}
		return candidate;
	}
	
	public void logout(Candidate candidate)
	{
		try{
			if(session.containsKey(candidate.getCandidateid()))
			{
				String userid = candidate.getCandidateid(); 
				session.remove(userid);
				logger.log(Level.INFO, userid + " logged out ");
				
				// remove the candidate object from HTTP session
				this.getThreadLocalRequest().getSession().removeAttribute("candidate");
				this.getThreadLocalRequest().getSession().invalidate();
			}
		}catch(Exception e)
		{
			logger.log(Level.INFO, "Failed to logout "+ e.getMessage());
		}
	}
	
	public static boolean checkLogin(Candidate candidate)
	throws SkillTestException
	{
		String userid = candidate.getCandidateid();
		if(session.containsKey(userid))
		{
			logger.log(Level.INFO, userid + " is currently logged in ");
			return true;
		}else
		{
			return false;
		}
	}
	
	public void addNewCandidate(Candidate candidate)
	throws SkillTestException
	{
		try{
			CandidateDAO.saveCandidate(candidate);
		}
		catch(Exception e){
			logger.log(Level.INFO, e.getMessage());
			if(e instanceof SkillTestException){
				throw (SkillTestException)e;
			}else{
				throw new SkillTestException(e);
			}
		}
	}
	
	// Debug
	public static void main(String[] args) {		
		try {
			SecurityServiceImpl s = new SecurityServiceImpl();
			s.login("lallu", "pappu");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
